package com.sudo.boot.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;

public class ChatClient {

    public void start(String name) throws IOException {
        // 创建channel
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8888));
        // 接收服务端发过来的消息
        socketChannel.configureBlocking(false);
        // 获取selector
        Selector selector = Selector.open();
        // 注册channel到selector上，让selector对其读感兴趣
        socketChannel.register(selector, SelectionKey.OP_READ);

        // 创建线程，专门负责发送消息
        new SendMesThread(name, socketChannel).start();

        while (selector.select() > 0) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                // 服务端消息过来（广播）
                if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);

                    StringBuilder message = new StringBuilder();
                    while (channel.read(buffer) > 0) {
                        buffer.flip();
                        message.append(new String(buffer.array(), 0, buffer.limit(), StandardCharsets.UTF_8));
                        buffer.clear();
                    }
                    System.out.println(message);
                    channel.register(selector, SelectionKey.OP_READ);
                }
                iterator.remove();
            }
        }
    }
}

class SendMesThread extends Thread {
    private String name;
    // 要发消息到哪个channel
    private SocketChannel socketChannel;

    public SendMesThread(String name, SocketChannel socketChannel) {
        this.name = name;
        this.socketChannel = socketChannel;
    }

    public void run() {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String message = scanner.nextLine();
            String sendMes = name + ": " + message;
            if (!message.isEmpty()) {
                try {
                    socketChannel.write(ByteBuffer.wrap(sendMes.getBytes(StandardCharsets.UTF_8)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
